package controllers

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"library/models"
)

// 获取所有分类列表
func GetCategories(c *gin.Context) {
	var categories []models.Category
	DB.Find(&categories)
	c.HTML(http.StatusOK, "category_list.html", gin.H{"Categories": categories})
}

// 显示添加分类页面
func ShowAddCategoryPage(c *gin.Context) {
	c.HTML(http.StatusOK, "category_add.html", nil)
}

// 添加分类提交
func AddCategory(c *gin.Context) {
	name := c.PostForm("name")
	category := models.Category{Name: name}
	DB.Create(&category)

	// 操作日志
	log := models.Log{Action: "添加分类: " + name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/categories")
}

// 显示编辑分类页面
func ShowEditCategoryPage(c *gin.Context) {
	id := c.Param("id")
	var category models.Category
	DB.First(&category, id)
	c.HTML(http.StatusOK, "category_edit.html", gin.H{"Category": category})
}

// 编辑分类提交
func EditCategory(c *gin.Context) {
	id := c.Param("id")
	name := c.PostForm("name")
	var category models.Category
	DB.First(&category, id)
	category.Name = name
	DB.Save(&category)

	// 操作日志
	log := models.Log{Action: "编辑分类: " + name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/categories")
}

// 删除分类
func DeleteCategory(c *gin.Context) {
	id := c.Param("id")
	var category models.Category
	DB.First(&category, id)
	DB.Delete(&category)

	// 操作日志
	log := models.Log{Action: "删除分类: " + category.Name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/categories")
}
